package cn.edu.zjgsu.ito.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cn.edu.zjgsu.ito.interceptor.TeacherControllerInterceptor;
import cn.edu.zjgsu.ito.service.ServiceFactory;
import cn.edu.zjgsu.ito.service.TeaScoreInputService;
import cn.edu.zjgsu.ito.util.ChineseTypeFilte;
import cn.edu.zjgsu.ito.util.GetTimeUtil;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

/**
 * @author norman
 * 成绩录入功能
 */

@Before(TeacherControllerInterceptor.class)
public class TeaScoreInputController extends Controller{
	private String uuid;
	private String teaId;
	private String teaName;
	private String courseName;
	private String courseNo;
	private String gradeSystem;
	private String usual;
	private String experiment;
	private String final1;
	private String other;
	private UploadFile newfile=null;
	private String filePath;
	private String fileAddress;
	private String suffix;
	private String tip;
	private String flag;
	private String Json;
	private String type;
	private String fileName;
	private String gradeInfo;
	private String course;
	private String term;
	int a[]={0,0,0,0};
	String createTime=GetTimeUtil.dao.getTime();
	TeaScoreInputService teaScoreInputService = ServiceFactory.createTeaScoreInputService();
	public static final DateFormat formatter=new SimpleDateFormat("yyyyMMddHHmmss");

	/**
	 * 选择要录入成绩的课程
	 */
	public void index(){

		teaId=getSessionAttr("tNo");
		System.out.println(teaId);
		List<Record> r=teaScoreInputService.index(teaId);
		//课程超时判断
		teaScoreInputService.timeJudge();
		if(r==null){
			System.out.println("暂无课程录入");
			setAttr("noCourse","您暂时还未有课程需要录入成绩!");
			render("score.html");
		}
		else{
			System.out.println("存在录入的成绩");
			setAttr("course", r);
			render("score.html");
		}
	}

	/**
	 * 显示该课程的学生信息
	 * @throws ParseException 
	 */
	public void gradeSelected() throws ParseException{
		String testNo = getPara("testNo");

		Record testInf = Db.findFirst("select * from test where testNo=?",testNo);
		String uuid = testInf.getStr("uuid");
		String testType = testInf.getStr("testType");
		String testLock = testInf.getStr("testLock");
		System.out.println(uuid+"===="+testType+"====="+testLock);

		if(testType.equals("1")){//正考页面
			//返回页面学生信息
			List<Record> students = teaScoreInputService.gradeSelected(uuid,testType,testLock);
			if(testLock.equals("1") || testLock.equals("2")){
				setAttr("access","disabled class=\"disabled\"");
			}

			String system = "";//判断页面的应用格式
			String systemtemp = getPara("systemtemp");
			String usual = "";
			String experiment = "";
			String final1 = "";
			String other = "";

			//			String grade = students.get(0).getStr("grade");//没有成绩默认百分制
			//			
			//			if(grade.equals("A")||grade.equals("B")||grade.equals("C")||grade.equals("P")||grade.equals("F")){
			//				 system = "五级制";
			//			}else{
			//				 system = "百分制";
			//			}

			//			systemtemp.equals(1)的话就是从设置过来的   null  首页进来的。
			System.out.println(usual+"sssssssss"+systemtemp+final1);
			//设置第一次进页面比例的attr
			System.out.println(systemtemp+"这个哥哥哥哥哥哥哥");
			System.out.println(system+"前面");
			if(testLock.equals("0")){
				if(systemtemp == null){
					setAttr("usual","25");
					setAttr("experiment","25");
					setAttr("final1","25");
					setAttr("other","25");
					setAttr("system","百分制无");
					System.out.println("外面~~~~~~~~~");
				}else if(systemtemp.equals("1")){
					usual = getPara("usual");
					System.out.println(usual+"uuuuuuuuuuu");
					experiment = getPara("experiment");
					final1 = getPara("final1");
					other = getPara("other");
					system = ChineseTypeFilte.dao.getUTF8Chinese(getPara("select"));
					setAttr("usual",usual);
					setAttr("experiment",experiment);
					setAttr("final1",final1);
					setAttr("other",other);
					setAttr("system",system+"无");
				}
			}else{
				usual = students.get(0).getStr("dailyPercent");
				experiment = students.get(0).getStr("experimentalPercent");
				final1 = students.get(0).getStr("finalPercent");
				other = students.get(0).getStr("otherPercent");
				int binull = 0;
				for(int i = 0;i < students.size();i++){
					if(students.get(i).getStr("grade") != null && !students.get(i).getStr("grade").equals("未录入") && !students.get(i).getStr("grade").equals("旷考")&& !students.get(i).getStr("grade").equals("作弊")){
						binull = i;
					}
				}
				String grade = students.get(binull).getStr("grade");//没有成绩默认百分制

				if(grade.equals("A")||grade.equals("B")||grade.equals("C")||grade.equals("P")||grade.equals("F")){
					system = "五级制";
				}else{
					system = "百分制";
				}
				System.out.println(usual+"sssssssss"+systemtemp+final1);
				setAttr("system",system);
				setAttr("usual",usual);
				setAttr("experiment",experiment);
				setAttr("final1",final1);
				setAttr("other",other);
			}

			if(system.equals("五级制")){
				setAttr("fiveSelect","selected");
			}else if(system.equals("百分制")){
				setAttr("hundredSelect","selected");
			}

			setAttr("students",students);

			setAttr("testType",testType);//给前台判断
			setAttr("testNo",testNo);
			System.out.println(system+"fgggggggggggggg");
			render("marking.html");
		}else if(testType.equals("2")){//补考页面

			List<Record> students = teaScoreInputService.gradePraSelected(testNo);
			if(testLock.equals("1") || testLock.equals("2")){
				setAttr("access","disabled class=\"disabled\"");
			}

			String system = "";//判断页面的应用格式
			String systemtemp = getPara("systemtemp");
			if(testLock.equals("0")){
				if(systemtemp == null){
					setAttr("system","百分制无");
				}else if(systemtemp.equals("1")){
					system = ChineseTypeFilte.dao.getUTF8Chinese(getPara("select"));
					setAttr("system",system+"无");
				}
			}else{
				String grade = "";
				for(int i = 0;i < students.size();i++){
					if( students.get(i).getStr("grade") != null &&  !students.get(i).getStr("grade").equals("未录入") && !students.get(i).getStr("grade").equals("旷考")&& !students.get(i).getStr("grade").equals("作弊")){
						grade = students.get(i).getStr("grade");//没有成绩默认百分制
					}
				}
				System.out.println("判断前台页面格式的成绩："+ grade);
				if(grade.equals("A")||grade.equals("B")||grade.equals("C")||grade.equals("P")||grade.equals("F")){
					system = "五级制";
				}else{
					system = "百分制";
				}
				setAttr("system",system);
			}

			if(system.equals("五级制")){
				setAttr("fiveSelect","selected");
			}else if(system.equals("百分制")){
				setAttr("hundredSelect","selected");
			}
			System.out.println("考试制度："+system);
			setAttr("students",students);
			setAttr("testLock",testLock);
			setAttr("testType",testType);//给前台判断
			setAttr("testNo",testNo);

			render("replacescore.html");
		}
	}
	
	
	public void gradeSelected(String testNo) throws ParseException{

		Record testInf = Db.findFirst("select * from test where testNo=?",testNo);
		String uuid = testInf.getStr("uuid");
		String testType = testInf.getStr("testType");
		String testLock = testInf.getStr("testLock");
		System.out.println(uuid+"===="+testType+"====="+testLock);

		if(testType.equals("1")){//正考页面
			//返回页面学生信息
			List<Record> students = teaScoreInputService.gradeSelected(uuid,testType,testLock);
			if(testLock.equals("1") || testLock.equals("2")){
				setAttr("access","disabled class=\"disabled\"");
			}

			String system = "";//判断页面的应用格式
			String systemtemp = getPara("systemtemp");
			String usual = "";
			String experiment = "";
			String final1 = "";
			String other = "";

			//			String grade = students.get(0).getStr("grade");//没有成绩默认百分制
			//			
			//			if(grade.equals("A")||grade.equals("B")||grade.equals("C")||grade.equals("P")||grade.equals("F")){
			//				 system = "五级制";
			//			}else{
			//				 system = "百分制";
			//			}

			//			systemtemp.equals(1)的话就是从设置过来的   null  首页进来的。
			System.out.println(usual+"sssssssss"+systemtemp+final1);
			//设置第一次进页面比例的attr
			System.out.println(systemtemp+"这个哥哥哥哥哥哥哥");
			System.out.println(system+"前面");
			if(testLock.equals("0")){
				if(systemtemp == null){
					setAttr("usual","25");
					setAttr("experiment","25");
					setAttr("final1","25");
					setAttr("other","25");
					setAttr("system","百分制无");
					System.out.println("外面~~~~~~~~~");
				}else if(systemtemp.equals("1")){
					usual = getPara("usual");
					System.out.println(usual+"uuuuuuuuuuu");
					experiment = getPara("experiment");
					final1 = getPara("final1");
					other = getPara("other");
					system = ChineseTypeFilte.dao.getUTF8Chinese(getPara("select"));
					setAttr("usual",usual);
					setAttr("experiment",experiment);
					setAttr("final1",final1);
					setAttr("other",other);
					setAttr("system",system+"无");
				}
			}else{
				usual = students.get(0).getStr("dailyPercent");
				experiment = students.get(0).getStr("experimentalPercent");
				final1 = students.get(0).getStr("finalPercent");
				other = students.get(0).getStr("otherPercent");
				int binull = 0;
				for(int i = 0;i < students.size();i++){
					if(students.get(i).getStr("grade") != null && !students.get(i).getStr("grade").equals("未录入") && !students.get(i).getStr("grade").equals("旷考")&& !students.get(i).getStr("grade").equals("作弊")){
						binull = i;
					}
				}
				String grade = students.get(binull).getStr("grade");//没有成绩默认百分制

				if(grade.equals("A")||grade.equals("B")||grade.equals("C")||grade.equals("P")||grade.equals("F")){
					system = "五级制";
				}else{
					system = "百分制";
				}
				System.out.println(usual+"sssssssss"+systemtemp+final1);
				setAttr("system",system);
				setAttr("usual",usual);
				setAttr("experiment",experiment);
				setAttr("final1",final1);
				setAttr("other",other);
			}

			if(system.equals("五级制")){
				setAttr("fiveSelect","selected");
			}else if(system.equals("百分制")){
				setAttr("hundredSelect","selected");
			}

			setAttr("students",students);

			setAttr("testType",testType);//给前台判断
			setAttr("testNo",testNo);
			System.out.println(system+"fgggggggggggggg");
			render("marking.html");
		}else if(testType.equals("2")){//补考页面

			List<Record> students = teaScoreInputService.gradePraSelected(testNo);
			if(testLock.equals("1") || testLock.equals("2")){
				setAttr("access","disabled class=\"disabled\"");
			}

			String system = "";//判断页面的应用格式
			String systemtemp = getPara("systemtemp");
			if(testLock.equals("0")){
				if(systemtemp == null){
					setAttr("system","百分制无");
				}else if(systemtemp.equals("1")){
					system = ChineseTypeFilte.dao.getUTF8Chinese(getPara("select"));
					setAttr("system",system+"无");
				}
			}else{
				String grade = "";
				for(int i = 0;i < students.size();i++){
					if( students.get(i).getStr("grade") != null &&  !students.get(i).getStr("grade").equals("未录入") && !students.get(i).getStr("grade").equals("旷考")&& !students.get(i).getStr("grade").equals("作弊")){
						grade = students.get(i).getStr("grade");//没有成绩默认百分制
					}
				}
				System.out.println("判断前台页面格式的成绩："+ grade);
				if(grade.equals("A")||grade.equals("B")||grade.equals("C")||grade.equals("P")||grade.equals("F")){
					system = "五级制";
				}else{
					system = "百分制";
				}
				setAttr("system",system);
			}

			if(system.equals("五级制")){
				setAttr("fiveSelect","selected");
			}else if(system.equals("百分制")){
				setAttr("hundredSelect","selected");
			}
			System.out.println("考试制度："+system);
			setAttr("students",students);
			setAttr("testLock",testLock);
			setAttr("testType",testType);//给前台判断
			setAttr("testNo",testNo);

			render("replacescore.html");
		}
	}



	/**
	 * 成绩设定
	 */
	public void setGrade(){

		String usual = getPara("usual");
		String experiment = getPara("experiment");
		String final1 = getPara("final1");
		String other = getPara("other");
		String select = getPara("select");
		String testNo = getPara("testNo");
		System.out.println(usual + other  + select +"333333333");
		int ret = teaScoreInputService.setGrade(usual,experiment,final1,other);

		System.out.println(ret+"tttttttttttt");
		if(ret == 1){
			//			Map<String,String> temp = new HashMap<String,String>();
			//			temp.put("usual",usual);
			//			temp.put("experiment",experiment);
			//			temp.put("final1",final1);
			//			temp.put("other",other);
			//			temp.put("select",select);
			//			System.out.println(select+"ggggggggggggggggg");
			//			temp.put("systemtemp","1");
			//			renderJson(temp);

			int selectTestLock = teaScoreInputService.selectTestLock(testNo);
			if(selectTestLock == 1){//已有成绩
				teaScoreInputService.setGradeBi(testNo,usual, experiment, other, final1);
			}
			renderJson(1);
		}
	}

	/**
	 * 给空的成绩设定为0
	 */
	public String judgeGrade(String grade){
		if(grade.trim().equals("")||grade.trim().equals("0")){
			return "0";
		}
		else{
			return grade;
		}
	}

	/**
	 * 比例导出功能
	 * @throws ParseException 
	 */
	public void export() throws ParseException{
		term = getPara("term");
		System.out.println(term);
		usual = getPara("usual");
		experiment = getPara("experiment");
		final1 = getPara("final");
		other = getPara("other");
		courseNo = ChineseTypeFilte.dao.getUTF8Chinese(getPara("courseNo"));
		uuid = ChineseTypeFilte.dao.getUTF8Chinese(getPara("uuid"));
		gradeSystem = getPara("selectGrade");
		System.out.println(usual+experiment+final1+other+gradeSystem+uuid);
		//System.out.println(gradeSystem);
		courseName=teaScoreInputService.lookcourseName(courseNo);
		teaId=getSessionAttr("tNo");		
		Record r = teaScoreInputService.lookTeaName(teaId);
		teaName = r.get("tName");		
		List<Record> students=teaScoreInputService.lookStudentsInfo(uuid);

		System.out.println("学生"+students.size());

		//创建Excel工作簿
		XSSFWorkbook workbook=new XSSFWorkbook();
		//创建一个工作表
		XSSFSheet sheet=workbook.createSheet();
		//创建第一行
		XSSFRow row = sheet.createRow(0);
		XSSFCell cell=null;
		//插入第一行数据
		cell=row.createCell(0);
		cell.setCellValue("护照号");
		cell=row.createCell(1);
		cell.setCellValue("姓");
		cell=row.createCell(2);
		cell.setCellValue("名");
		cell=row.createCell(3);
		cell.setCellValue("专业");
		cell=row.createCell(4);
		cell.setCellValue("入学年份");
		cell=row.createCell(5);
		cell.setCellValue("入学季度");
		int x=0;
		int num=5;
		num=teaScoreInputService.judge(usual,experiment,final1,other,num,a);
		for(int j=0;j<a.length;j++){
			//System.out.println(a[j]);
		}
		//System.out.println(num);
		if(num==5){
			cell=row.createCell(6);
			cell.setCellValue("平时成绩");
			cell=row.createCell(7);
			cell.setCellValue("实验成绩");
			cell=row.createCell(8);
			cell.setCellValue("期末成绩");
			cell=row.createCell(9);
			cell.setCellValue("其他成绩");
		}
		else{
			for(int m=6;m<=num;m++){
				cell=row.createCell(m);
				for(int n=x;n<4;n++){
					if(a[n]!=0){
						switch (n) {
						case 0:
							cell.setCellValue("平时成绩");
							x=n+1;
							break;
						case 1:
							cell.setCellValue("实验成绩");
							x=n+1;
							break;
						case 2:
							cell.setCellValue("期末成绩");
							x=n+1;						
							break;
						case 3:
							cell.setCellValue("其他成绩");
							x=n+1;
							break;
						}

						break;
					}
					//System.out.println("加"+x);
				}
			}
		}	
		String[] level = {"A","B","C","P","F"};
		XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
		XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
				.createExplicitListConstraint(level);
		CellRangeAddressList addressList = null;
		XSSFDataValidation validation = null;
		for(int i=1;i<=students.size();i++){
			XSSFRow nextrow=sheet.createRow(i);
			XSSFCell cell2=nextrow.createCell(0);
			cell2.setCellValue(students.get(i-1).get("newpassportNo").toString());
			cell2=nextrow.createCell(1);
			cell2.setCellValue(students.get(i-1).get("firstName").toString());
			cell2=nextrow.createCell(2);
			cell2.setCellValue(students.get(i-1).get("lastName").toString());
			cell2=nextrow.createCell(3);
			cell2.setCellValue(students.get(i-1).get("majorName").toString());
			cell2=nextrow.createCell(4);
			cell2.setCellValue(students.get(i-1).get("eduStartDate").toString());
			cell2=nextrow.createCell(5);
			cell2.setCellValue(students.get(i-1).get("eduSeason").toString());
			if(num==5){
				if(gradeSystem.equals("五级制")){
					for (int j = 6; j <= 9; j++) {
						addressList = new CellRangeAddressList(i, i, j, j);
						validation = (XSSFDataValidation) dvHelper.createValidation(
								dvConstraint, addressList);
						// 07默认setSuppressDropDownArrow(true);
						// validation.setSuppressDropDownArrow(true);
						// validation.setShowErrorBox(true);
						sheet.addValidationData(validation);
					}
				}
				else{
					for (int j = 6; j <= 9; j++) {
						cell2=nextrow.createCell(j);
						cell2.setCellValue("");
					}
				}
			}
			else{
				if(gradeSystem.equals("五级制")){
					for (int j = 6; j <= num; j++) {
						addressList = new CellRangeAddressList(i, i, j, j);
						validation = (XSSFDataValidation) dvHelper.createValidation(
								dvConstraint, addressList);
						// 07默认setSuppressDropDownArrow(true);
						// validation.setSuppressDropDownArrow(true);
						// validation.setShowErrorBox(true);
						sheet.addValidationData(validation);
					}
				}
				else{
					for (int j = 6; j <= num; j++) {
						cell2=nextrow.createCell(j);
						cell2.setCellValue("");
					}
				}
			}
		}

		//创建一个文件
		//System.out.println(createTime);
		fileAddress=PathKit.getWebRootPath()+"/exportFile/"+courseName.replace(" ", "_")+createTime+".xlsx";

		File file=new File(fileAddress);
		System.out.println(fileAddress);
		try {
			file.createNewFile();
			//将excel的内容存盘
			FileOutputStream stream=FileUtils.openOutputStream(file);
			workbook.write(stream);
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		type="excel";
		fileName=courseName+createTime+".xlsx";
		tip=teaScoreInputService.insertTemplate(type,fileName,fileAddress,teaName,createTime);
		System.out.println(tip);
		renderFile(file);
	}

	/**
	 * excel导入功能
	 */
	public void import1(){
		System.out.println("导入excel");

		filePath = PathKit.getWebRootPath()+"\\importFile\\";
		newfile=getFile("template", filePath);
		usual = getPara("usual");
		experiment = getPara("experiment");

		final1 = getPara("final1");
		other = getPara("other");
		gradeSystem = getPara("selectGrade");
		System.out.println(usual+experiment+final1+other+gradeSystem);

		fileAddress = filePath+newfile.getFileName();

		suffix=newfile.getFileName().substring(newfile.getFileName().lastIndexOf("."),newfile.getFileName().length());//da:文件的后缀
		System.out.println(suffix);

		teaId=getSessionAttr("tNo");		
		Record r = teaScoreInputService.lookTeaName(teaId);
		teaName = r.get("tName");

		//String grades[] = new String[100];
		int count;
		if(suffix.equals(".xls")){
			System.out.println("3:"+fileAddress);
			File file = newfile.getFile();
			try {
				//创建Excel,读取文件内容
				HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(file));
				//获取第一个工作表
				//HSSFSheet sheet = workbook.getSheet("sheet0");
				HSSFSheet sheet = workbook.getSheetAt(0);
				int firstRowNum=0;
				int lastRowNum=sheet.getLastRowNum();
				int k;

				Json="[";
				for (int i = 1; i <= lastRowNum; i++) {
					String[] grades= new String[100];
					count=0;
					HSSFRow row = sheet.getRow(i);
					int lastCellNum=row.getLastCellNum();
					Json+="{";
					for (int j = 0; j < lastCellNum; j++) {

						HSSFCell cell = row.getCell(j);
						String value = teaScoreInputService.getHCellValue(cell);										
						Json+=" \"grade"+j+"\" " + ":"+" \""+value+"\"" +",";	
						if(j>=6){						
							grades[count++]=value;											
						}						
					}
					String totalGrade=teaScoreInputService.calculate(usual,experiment,final1,other,gradeSystem,grades);

					Json+=" \"grade"+lastCellNum+"\" " + ":"+" \""+totalGrade+"\"";
					//Json=Json.substring(0,Json.lastIndexOf(","));
					Json+="},";
				}
				Json=Json.substring(0,Json.lastIndexOf(","));
				Json+="]";
				System.out.println(Json);

				type="excel";
				fileName=newfile.getOriginalFileName();				
				tip=teaScoreInputService.insertUploadFile(type,fileName,fileAddress,teaName,createTime);
				renderText(Json);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
			} 
		}
		else if(suffix.equals(".xlsx")){
			try {
				File file = newfile.getFile();
				//创建Excel,读取文件内容
				XSSFWorkbook workbook = new XSSFWorkbook(FileUtils.openInputStream(file));
				//获取第一个工作表
				//XSSFSheet sheet = workbook.getSheet("sheet0");
				XSSFSheet sheet = workbook.getSheetAt(0);
				int firstRowNum=0;
				int lastRowNum=sheet.getLastRowNum();
				int k;

				Json="[";
				for (int i = 1; i <= lastRowNum; i++) {
					String[] grades= new String[100];
					count=0;
					XSSFRow row = sheet.getRow(i);
					int lastCellNum=row.getLastCellNum();
					Json+="{";
					for (int j = 0; j < lastCellNum; j++) {						
						XSSFCell cell = row.getCell(j);
						String value = teaScoreInputService.getXCellValue(cell);						
						System.out.print(value +" ");					
						Json+=" \"grade"+j+"\" " + ":"+" \""+value+"\"" +",";	
						if(j>=6){						
							grades[count++]=value;											
						}						
					}
					String totalGrade=teaScoreInputService.calculate(usual,experiment,final1,other,gradeSystem,grades);

					System.out.println("结果"+totalGrade);
					Json+=" \"grade"+lastCellNum+"\" " + ":"+" \""+totalGrade+"\"";
					//Json=Json.substring(0,Json.lastIndexOf(","));
					Json+="},";					
				}
				Json=Json.substring(0,Json.lastIndexOf(","));
				Json+="]";
				System.out.println(Json);

				type="excel";
				fileName=newfile.getOriginalFileName();				
				tip=teaScoreInputService.insertUploadFile(type,fileName,fileAddress,teaName,createTime);


				renderText(Json);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
			} 
		}
		else{
			System.out.println("删除");
			File file=new File(fileAddress);
			if(file.exists()){
				file.delete();
			}
			setAttr("tip","<script>alert(\"文件格式不正确,请选择excel\")</script>");
			render("score.html");
		}
	}

	/**
	 * 判断是正、补考提交保存
	 * */


	/**
	 * 提交成绩
	 */
	public void submitGrade(){

		String testType = getPara("testType");
		teaId=getSessionAttr("tNo");
		String gradesss = getPara("grade");
		System.out.println(gradesss);
		String testNo =getPara("testNo");
		String grades[] = gradesss.split(",");
		if(testType.equals("1")){//处理正考的期末成绩
			String usual = getPara("usual");
			String experiment = getPara("experiment");
			String final1 = getPara("final1");
			String other = getPara("other");
			String select = getPara("select");
			System.out.println(select+final1+"yyyyyyyyyyyyy");
			System.out.println(grades[0]+grades[1]+grades[2]);
			teaScoreInputService.submitGrades(grades,testNo,usual,experiment,other,final1,select,teaId);
			renderJson("1");
		}else if(testType.equals("2")){//处理补考的成绩
			System.out.println("补考成绩提交");
			System.out.println(testType+"====="+gradesss+"======="+testNo+"====");
			teaScoreInputService.submitGradesRep(grades,testNo,teaId);
			renderJson("1");
		}
	}


	/**
	 * 保存成绩
	 */
	public void saveGrade(){

		String testType = getPara("testType");
		teaId=getSessionAttr("tNo");
		String gradesss = getPara("grade");
		System.out.println(gradesss);
		String testNo =getPara("testNo");
		String grades[] = gradesss.split(",");
		//		System.out.println("成绩："+grades[1]+grades[2]+grades[3]+grades[4]+grades[5]+grades[6]);
		if(testType.equals("1")){//处理正考的期末成绩
			String usual = getPara("usual");
			String experiment = getPara("experiment");
			String final1 = getPara("final1");
			String other = getPara("other");
			String select = getPara("select");
			System.out.println(select+final1+"yyyyyyyyyyyyy");
			System.out.println(grades[0]+grades[1]+grades[2]);
			teaScoreInputService.saveGrades(grades,testNo,usual,experiment,other,final1,select,teaId);
			renderJson("1");
		}else if(testType.equals("2")){//处理补考的成绩
			System.out.println("补考成绩提交");
			System.out.println(testType+"====="+gradesss+"======="+testNo+"====");
			teaScoreInputService.saveGradesRep(grades,testNo,teaId);
			renderJson("1");
		}
	}

	/**
	 * 导出提交的成绩
	 */
	public void exportGrade(){

		System.out.println("导出成绩");
		String testNo = getPara("testNo") ;
		Record test = Db.findFirst("select * from test,teacher_info where test.tNo=teacher_info.tNo and testNo=?",testNo);
		String termValue = test.getStr("termValue");
		String term = termValue.replace("/","-");
		String courseNo = test.getStr("courseNo");
		String tNo = test.getStr("tNo");
		String tName = test.getStr("tName");
		OutputStream out = null;
		System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		Date date = new Date();
		String time=formatter.format(date);

		System.out.println(time);

		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\download\\";
		System.out.println("------1------");
		deleteFile(new File(filedir));//清空缓存区

		String temp = term + courseNo + tNo + tName + time +".xls";
		String outpath = filedir+temp;
		System.out.println(outpath);
		try {
			out = new FileOutputStream(outpath);
			teaScoreInputService.exportGrade(testNo,out);
			renderFile(new File(outpath));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	 		




		//		courseName=teaScoreInputService.lookcourseName(courseNo);
		//		term=getPara("term");
		//		List<Record> r2=teaScoreInputService.lookGradeInfo(uuid);
		//		System.out.println(r2.size());
		//		//创建Excel工作簿
		//		Record r = teaScoreInputService.lookTeaName(teaId);

		//		teaName = r.get("tName");
		//		
		//		XSSFWorkbook workbook=teaScoreInputService.createWorkbook(r2);
		//		fileAddress=PathKit.getWebRootPath()+"/exportFile/"+courseName.replace(" ", "_")+createTime+".xlsx";
		//		System.out.println(fileAddress);
		//		File file=new File(fileAddress);
		//		try {
		//			file.createNewFile();
		//			//将excel的内容存盘
		//			FileOutputStream stream=FileUtils.openOutputStream(file);
		//			workbook.write(stream);
		//			stream.close();
		//		} catch (IOException e) {
		//			e.printStackTrace();
		//		}
		//		type="excel";
		//		fileName=courseName+createTime+".xlsx";
		//		tip=teaScoreInputService.insertTemplate(type,fileName,fileAddress,teaName,createTime);
		//		System.out.println(tip);
		//		renderFile(file);
		//
		//		setAttr("groupMes", "<script>alert(\"任务组名已存在!\")</script>");
	}

	//导出补考成绩
	public void exportReplace(){

		System.out.println("导出补考成绩");
		String testNo = getPara("testNo") ;
		Record test = Db.findFirst("select * from test,teacher_info where test.tNo=teacher_info.tNo and testNo=?",testNo);
		String termValue = test.getStr("termValue");
		String term = termValue.replace("/","-");
		String courseNo = test.getStr("courseNo");
		String tNo = test.getStr("tNo");
		String tName = test.getStr("tName");
		OutputStream out = null;
		System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		Date date = new Date();
		String time=formatter.format(date);

		System.out.println(time);

		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\download\\";
		System.out.println("------1------");
		deleteFile(new File(filedir));//清空缓存区

		String temp = term + courseNo + tNo + tName + time +".xls";
		String outpath = filedir+temp;
		System.out.println(outpath);
		try {
			out = new FileOutputStream(outpath);
			teaScoreInputService.exportReplace(testNo,out);
			renderFile(new File(outpath));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	 		




		//		courseName=teaScoreInputService.lookcourseName(courseNo);
		//		term=getPara("term");
		//		List<Record> r2=teaScoreInputService.lookGradeInfo(uuid);
		//		System.out.println(r2.size());
		//		//创建Excel工作簿
		//		Record r = teaScoreInputService.lookTeaName(teaId);

		//		teaName = r.get("tName");
		//		
		//		XSSFWorkbook workbook=teaScoreInputService.createWorkbook(r2);
		//		fileAddress=PathKit.getWebRootPath()+"/exportFile/"+courseName.replace(" ", "_")+createTime+".xlsx";
		//		System.out.println(fileAddress);
		//		File file=new File(fileAddress);
		//		try {
		//			file.createNewFile();
		//			//将excel的内容存盘
		//			FileOutputStream stream=FileUtils.openOutputStream(file);
		//			workbook.write(stream);
		//			stream.close();
		//		} catch (IOException e) {
		//			e.printStackTrace();
		//		}
		//		type="excel";
		//		fileName=courseName+createTime+".xlsx";
		//		tip=teaScoreInputService.insertTemplate(type,fileName,fileAddress,teaName,createTime);
		//		System.out.println(tip);
		//		renderFile(file);
		//
		//		setAttr("groupMes", "<script>alert(\"任务组名已存在!\")</script>");

	}

	//教师成绩导入模板下载
	public void gradeModel(){
		String tNo = getSessionAttr("tNo");
		String testNo = getPara("testNo");
		//		System.out.println(tNo + uuid + "模板下载");
		//		String testNo = "26325236hsflenjkuz87655495";
		String stuName= "";
		OutputStream out = null;
		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\download\\";
		deleteFile(new File(filedir));//清空缓存区

		String temp ="学生成绩导入模板" +".xls";
		stuName= stuName + temp;
		String outpath = filedir+stuName;
		try {
			out = new FileOutputStream(outpath);
			System.out.println(filedir+stuName);
			teaScoreInputService.gradeModel(tNo, testNo, out);
			String path = filedir + stuName;
			renderFile(new File(path));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	 		
	}
	
	//补考成绩导入模板下载
	public void gradePreModel(){

		String tNo = getSessionAttr("tNo");
		String testNo = getPara("testNo");
		//		System.out.println(tNo + uuid + "模板下载");
		//		String testNo = "26325236hsflenjkuz87655495";
		String stuName= "";
		OutputStream out = null;
		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\download\\";
		deleteFile(new File(filedir));//清空缓存区

		String temp ="学生成绩导入模板" +".xls";
		stuName= stuName + temp;
		String outpath = filedir+stuName;
		try {
			out = new FileOutputStream(outpath);
			System.out.println(filedir+stuName);
			teaScoreInputService.gradePreModel(tNo, testNo, out);
			String path = filedir + stuName;
			renderFile(new File(path));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	 		
	
	}

	//成绩导入
	public void importGrade(){
		String testNo = getPara("testNo");
		System.out.println("考试号："+ testNo);
		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\upload";
		try
		{
			UploadFile file=getFile("uploadFile");
			String fileName=file.getFileName();
			String extension=fileName.substring(fileName.lastIndexOf("."));
			if(extension.equals(".xls")||extension.equals(".XLS"))
			{
				File source=file.getFile();
				String newFileName=System.currentTimeMillis()+extension;
				FileInputStream fis=new FileInputStream(source);
				File targetDir=new File(filedir);
				File target=new File(targetDir,newFileName);
				FileOutputStream fos=new FileOutputStream(target);
				byte[] bts=new byte[300];
				while (fis.read(bts,0,300)!=-1){
					fos.write(bts,0,300);
				}
				String abc = filedir+"\\"+newFileName;

				InputStream verifyData = new FileInputStream(abc);

				String status = teaScoreInputService.importGrade(verifyData,testNo);
				setAttr("status",status);
				fos.close();
				fis.close();
//				index();
				gradeSelected(testNo);
//				render("marking.html");
			}
			else
			{
				setAttr("error","文件类型错误");
				index();
				//				renderFreeMarker("/WEB-INF/param/param.html");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	//补考成绩导入
		public void importPreGrade(){
			String testNo = getPara("testNo");
			System.out.println("考试号："+ testNo);
			String filedir=PathKit.getWebRootPath();
			filedir=filedir+"\\WEB-INF\\upload";
			try
			{
				UploadFile file=getFile("uploadFile");
				String fileName=file.getFileName();
				String extension=fileName.substring(fileName.lastIndexOf("."));
				if(extension.equals(".xls")||extension.equals(".XLS"))
				{
					File source=file.getFile();
					String newFileName=System.currentTimeMillis()+extension;
					FileInputStream fis=new FileInputStream(source);
					File targetDir=new File(filedir);
					File target=new File(targetDir,newFileName);
					FileOutputStream fos=new FileOutputStream(target);
					byte[] bts=new byte[300];
					while (fis.read(bts,0,300)!=-1){
						fos.write(bts,0,300);
					}
					String abc = filedir+"\\"+newFileName;

					InputStream verifyData = new FileInputStream(abc);

					String status = teaScoreInputService.importPreGrade(verifyData,testNo);
					setAttr("status",status);
					fos.close();
					fis.close();
					gradeSelected(testNo);
				}
				else
				{
					setAttr("error","文件类型错误");
					index();
					//				renderFreeMarker("/WEB-INF/param/param.html");
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}

	//重置
	public void reset(){
		String testNo = getPara("testNo");
		Db.update("update test set testLock='0' where testNo=?",testNo);
		Db.update("delete from student_grade where testNo=?",testNo);
		try {
			gradeSelected();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void deleteFile(File oldPath) {
		if (oldPath.isDirectory()) {
			File[] files = oldPath.listFiles();
			for (File file : files) {
				deleteFile(file);
			}
		}else{
			oldPath.delete();
		}
	}
}
